package cn.fl.institution.controller;

import cmm.comm.facade.livecheck.api.ICmmLiveChkApiService;
import cmm.comm.facade.livecheck.dto.CmmLiveChkDTO;
import cmm.mid.core.framework.constant.tripartite.InterfaceConstants;
import cmm.mid.core.framework.dto.BaseParamDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.commons.result.ResponseData;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.preloan.dto.financialinterface.OpenAccountApplyRequest;
import cn.fl.preloan.dto.financialinterface.OpenAccountValidationRequest;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.preloan.financialinterface.IFinancialService;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjCstAccInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.customer.facade.customer.dto.CstBscInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 项目基础信息表 控制层 亿联银行
 */
@Controller
@RequestMapping("/institution/ylbank")
public class PrjBscInfoInsYlbankController {

    @Autowired
    private IProjectApiService projectApiService;

    @Autowired
    private ICstBscInfoService cstBscInfoService;

    @Autowired
    private ICstNpBscInfoService cstNpBscInfoService;

    @Autowired
    private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表

    @Autowired
    private ICmmLiveChkApiService cmmLiveChkApiService;

    @Autowired
    private IPrjBscInfoService prjBscInfoService;

    @Autowired
    private IFinancialService financialService;

    /**
     * 保存 项目客户信息
     */
    @RequestMapping(value = "/ylBankPrjAccInfo.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO ylBankPrjAccInfo(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("亿联银行信息采集新增修改Start,request:{}" , JSON.toJSONString(request.getParameterMap())).info();
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存数据成功");
        String prjId = request.getParameter("prjId");
        String insCode = request.getParameter("insCode");
        String cstId = request.getParameter("cstId");
        String cstNm = request.getParameter("cstNm");
        String certNo = request.getParameter("certNo");
        String domicileProvince = request.getParameter("domicileProvince");
        String domicileCity = request.getParameter("domicileCity");
        String idAddr = request.getParameter("idAddr");
        String issuingOrg = request.getParameter("issuingOrg");
        String postProvince = request.getParameter("postProvince");
        String postCity = request.getParameter("postCity");
        String postAddr = request.getParameter("postAddr");
        String highDgCd = request.getParameter("highDgCd");
        String nation = request.getParameter("nation");
        String certValidSDt = request.getParameter("certValidSDt");
        String certValidEDt = request.getParameter("certValidEDt");
        String monthInc = request.getParameter("monthInc");
        String indCd = request.getParameter("indCd");

        try {
            if (StringUtils.isBlank(prjId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目ID为空!");
            }
            if (StringUtils.isBlank(cstId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户ID为空!");
            }
            if (StringUtils.isBlank(domicileProvince)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "身份证所在地省为空!");
            }
            if (StringUtils.isBlank(domicileCity)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "身份证所在地市为空!");
            }
            if (StringUtils.isBlank(idAddr)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "身份证详细地址为空!");
            }
            if (StringUtils.isBlank(issuingOrg)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "证件签发机关为空!");
            }
            if (StringUtils.isBlank(postProvince)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "家庭地址省空!");
            }
            if (StringUtils.isBlank(postCity)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "家庭地址市为空!");
            }
            if (StringUtils.isBlank(postAddr)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "家庭地址详细地址为空!");
            }
            if (StringUtils.isBlank(nation)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "民族为空!");
            }
            if (StringUtils.isBlank(certValidSDt)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "证件有效起始日期为空!");
            }
            if (StringUtils.isBlank(certValidEDt)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "证件有效终止日期为空!");
            }
            if (StringUtils.isBlank(monthInc)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "月收入为空!");
            }
            if (StringUtils.isBlank(indCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "行业为空!");
            }
            if (StringUtils.isBlank(highDgCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "学历为空!");
            }

            //根据id查询项目信息
            BaseLogUtils.newLogger("亿联银行保存信息,查询项目信息Start,prjId:{}", prjId).info();
            PrjBscInfoDTO prjBscInfoDTO = this.projectApiService.selectById(Long.valueOf(prjId), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            BaseLogUtils.newLogger("亿联银行保存信息,查询项目信息End,prjId:{},prjBscInfoDTO:{}", prjId, JSON.toJSONString(prjBscInfoDTO)).info();
            if (null == prjBscInfoDTO) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "查询项目为空!");
            }
            if (!cstId.equals(String.valueOf(prjBscInfoDTO.getCstId()))) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户ID不匹配!");
            }
            BaseLogUtils.newLogger("亿联银行保存信息,获取客户信息Start,prjId:{},cstId:{}", prjId, prjBscInfoDTO.getCstId()).info();
            CstBscInfoDTO cstBscInfoDTO = this.cstBscInfoService.selectCstBscInfoById(prjBscInfoDTO.getCstId(), prjBscInfoDTO.getBuOrgCd());
            BaseLogUtils.newLogger("亿联银行保存信息,获取客户信息End,prjId,cstId:{},cstBscInfoDTO:{}", prjId, prjBscInfoDTO.getCstId(), JSON.toJSONString(cstBscInfoDTO)).info();
            // 有些字段数据CstBscInfo接口保存不上 额外处理一下CstNpBscInfo
            BaseLogUtils.newLogger("亿联银行保存信息,获取自然人信息Start,prjId:{},cstId:{}", prjId, prjBscInfoDTO.getCstId()).info();
            CstNpBscInfoVO cstNpBscInfoVO = this.cstNpBscInfoService.selectById(prjBscInfoDTO.getCstId());
            BaseLogUtils.newLogger("亿联银行保存信息,获取自然人信息End,prjId,cstId:{},cstNpBscInfoVO:{}", prjId, prjBscInfoDTO.getCstId(), JSON.toJSONString(cstNpBscInfoVO)).info();
            if (null != cstBscInfoDTO) {
                if (!Objects.equals(indCd, cstBscInfoDTO.getIndCd())) {
                    cstBscInfoDTO.setIndCd(indCd);
                    BaseLogUtils.newLogger("亿联银行保存信息,保存客户信息Start,prjId:{},cstBscInfoDTO:{}", prjId, JSON.toJSONString(cstBscInfoDTO)).info();
                    boolean modify = this.cstBscInfoService.modifyCstBscInfo(cstBscInfoDTO);
                    BaseLogUtils.newLogger("亿联银行保存信息,保存客户信息End,prjId:{},modify:{}", prjId, modify).info();
                }

            }
            boolean flag = false;
            if (null != cstNpBscInfoVO) {
                if (!Objects.equals(domicileProvince, cstNpBscInfoVO.getDomicileProvince())) {
                    cstNpBscInfoVO.setDomicileProvince(domicileProvince);
                    flag = true;
                }
                if (!Objects.equals(domicileCity, cstNpBscInfoVO.getDomicleCity())) {
                    cstNpBscInfoVO.setDomicleCity(domicileCity);
                    flag = true;
                }
                if (!Objects.equals(idAddr, cstNpBscInfoVO.getIdAddr())) {
                    cstNpBscInfoVO.setIdAddr(idAddr);
                    flag = true;
                }
                if (!Objects.equals(issuingOrg, cstNpBscInfoVO.getIssuingOrg())) {
                    cstNpBscInfoVO.setIssuingOrg(issuingOrg);
                    flag = true;
                }
                if (!Objects.equals(postProvince, cstNpBscInfoVO.getPostProvince())) {
                    cstNpBscInfoVO.setPostProvince(postProvince);
                    flag = true;
                }
                if (!Objects.equals(postCity, cstNpBscInfoVO.getPostCity())) {
                    cstNpBscInfoVO.setPostCity(postCity);
                    flag = true;
                }
                if (!Objects.equals(postAddr, cstNpBscInfoVO.getPostAddr())) {
                    cstNpBscInfoVO.setPostAddr(postAddr);
                    flag = true;
                }
                if (!Objects.equals(nation, cstNpBscInfoVO.getNation())) {
                    cstNpBscInfoVO.setNation(nation);
                    flag = true;
                }
                if (!Objects.equals(certValidSDt, cstNpBscInfoVO.getCertValidSDt())) {
                    cstNpBscInfoVO.setCertValidSDt(certValidSDt);
                    flag = true;
                }
                if (!Objects.equals(certValidEDt, cstNpBscInfoVO.getCertValidEDt())) {
                    cstNpBscInfoVO.setCertValidEDt(certValidEDt);
                    flag = true;
                }
                if (!Objects.equals(highDgCd, cstNpBscInfoVO.getHighDgCd())) {
                    cstNpBscInfoVO.setHighDgCd(highDgCd);
                    flag = true;
                }
                Long mrIncMoney = DecimalUtils.convertYuanToFen(Double.valueOf(monthInc));
                // 月收入转换年收入
                Double yrInc = DecimalUtils.mul(mrIncMoney.doubleValue(), 12d);
                if (!Objects.equals(cstNpBscInfoVO.getYrInc().doubleValue(), yrInc)) {
                    cstNpBscInfoVO.setYrInc(yrInc.longValue());
                    flag = true;
                }
            }
            BaseLogUtils.newLogger("亿联银行保存信息,是否保存客户信息,prjId:{},flag:{}", prjId, flag).info();
            if (flag) {
                BaseLogUtils.newLogger("亿联银行保存信息,保存自然人信息Start,prjId:{},cstNpBscInfoVO:{}", prjId, JSON.toJSONString(cstNpBscInfoVO)).info();
                boolean modify = this.cstNpBscInfoService.modify(cstNpBscInfoVO);
                BaseLogUtils.newLogger("亿联银行保存信息,保存自然人信息End,prjId:{},modify:{}", prjId, modify).info();
            }
        } catch (BaseException ex) {
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("亿联银行保存信息,异常:prjId:{},ex:{}" , prjId,JSONObject.toJSONString(ex.getMessage())).info();
        } catch (Exception e) {
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("亿联银行保存信息,系统异常");
            BaseLogUtils.newLogger("亿联银行保存信息,系统异常:prjId:{},e:{}" , prjId,JSONObject.toJSONString(e.getMessage())).error(BaseExceptionConstant.INTERFACE_0102);
            return resultVO;
        }
        BaseLogUtils.newLogger("亿联银行保存信息End,prjId:{},resultVO:{}", prjId, JSONObject.toJSONString(resultVO)).info();
        return resultVO;
    }

    /**
     * 获取验证码
     */
    @RequestMapping(value = "/getVerificationCodeForYlbank.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object getVerificationCodeForYlbank(Long prjId, PrjCstAccInfoQueryCondition prjCstAccInfoQC) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "四要素校验通过");
        BaseLogUtils.newLogger("getVerificationCodeForYlbank.亿联银行获取验证码，prjId:{}.prjCstAccInfoQC:{}",prjId,JSONObject.toJSONString(prjCstAccInfoQC)).info();
        // 开户银行
        if (StringUtils.isBlank(prjCstAccInfoQC.getBkCd()) || StringUtils.isBlank(prjCstAccInfoQC.getBkNm())) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请输入开户银行!");
            return result;
        }
        // 银行账号
        if (StringUtils.isBlank(prjCstAccInfoQC.getAccNo())) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请输入银行账号!");
            return result;
        }
        // 客户手机号
        if (StringUtils.isBlank(prjCstAccInfoQC.getMp())) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请输入手机号!");
            return result;
        }
        try {
            //获取验证码
            OpenAccountApplyRequest openAccountApplyRequest = new OpenAccountApplyRequest();
            PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
            BaseParamDTO baseParamDTO = new BaseParamDTO();
            DataResultDTO dataResultDTO = this.cmmLiveChkApiService.getAllLiveChkByCstId(baseParamDTO, String.valueOf(prjBscInfoVO.getCstId()), prjBscInfoVO.getLsCntNo());
            BaseLogUtils.newLogger("亿联换绑卡获取活体检测id：prjId={}, dataDTO={}", prjId, JSON.toJSONString(dataResultDTO)).info();
            if (dataResultDTO != null && 1 == dataResultDTO.getSuccess()) {
                List<CmmLiveChkDTO> cmmLiveChkDTOList = (List<CmmLiveChkDTO>) dataResultDTO.getData();
                if (CollectionUtils.isNotEmpty(cmmLiveChkDTOList) && cmmLiveChkDTOList.get(0).getId() != null) {
                    openAccountApplyRequest.setCmmLiveChkId(cmmLiveChkDTOList.get(0).getId().toString());
                }
            }
            openAccountApplyRequest.setBizSN(String.valueOf(prjId));
            openAccountApplyRequest.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_YLBANK);
            openAccountApplyRequest.setCustomerId(String.valueOf(prjBscInfoVO.getCstId()));
            openAccountApplyRequest.setCustomerName(prjBscInfoVO.getCstNm());
            openAccountApplyRequest.setIdCardNo(prjCstAccInfoQC.getCertNo());
            openAccountApplyRequest.setMobilePhone(prjCstAccInfoQC.getMp());
            openAccountApplyRequest.setBankCardNo(prjCstAccInfoQC.getAccNo());
            openAccountApplyRequest.setBankName(prjCstAccInfoQC.getBkNm());
            openAccountApplyRequest.setBankCode(prjCstAccInfoQC.getBkCd());
            BaseLogUtils.newLogger("亿联换绑卡调用获取验证码接口Begin：prjId={}, request={}", prjId, JSON.toJSONString(openAccountApplyRequest)).info();
            ResponseData responseData = this.financialService.openAccountApply(openAccountApplyRequest);
            BaseLogUtils.newLogger("亿联换绑卡调用获取验证码接口End:prjId={}, response={}", prjId, JSON.toJSONString(responseData)).info();
            if (PreloanResultCodeEnum.SUCCESS.getCode().equals(responseData.getCode())) {
                String openAccountStatus = (String) responseData.getData();
                if ("SUCCESS".equals(openAccountStatus) || "PROCESSING".equals(openAccountStatus)) {
                    result.setSuccess(BaseConstant.IS_YESNO_YES);
                    result.setInfo("验证码已发送至客户手机");
                    return result;
                }
            }
            //发送验证码失败
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("发送验证码失败失败：" + responseData.getMessage());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("亿联银行获取验证码失败 " + ex.getMessage()).info();
            ex.printStackTrace();
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("获取验证码失败!");
            BaseLogUtils.newLogger("亿联银行获取验证码失败,系统异常 " + ex.getMessage()).info();
            ex.printStackTrace();
        }
        return result;
    }

    //验证并换卡
    @RequestMapping(value = "/exchangeCardSaveForYl.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object exchangeCardSaveForYl(PrjCstAccInfoQueryCondition prjCstAccInfoQC,Long fundRasInsId,String verificationCode) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "绑卡成功");
        BaseLogUtils.newLogger("亿联银行换卡保存项目客户账户信息Strat： prjCstAccInfoQC：{} ",JSONObject.toJSONString(prjCstAccInfoQC)).info();

        try {

            BaseLogUtils.newLogger("亿联银行换卡,机构id： fundRasInsId = {} ",fundRasInsId).info();
            OpenAccountValidationRequest openAccountValidationRequest = new OpenAccountValidationRequest();
            openAccountValidationRequest.setBizSN(String.valueOf(prjCstAccInfoQC.getPrjId()));
            openAccountValidationRequest.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_YLBANK);
            openAccountValidationRequest.setCustomerId(String.valueOf(prjCstAccInfoQC.getCstId()));
            openAccountValidationRequest.setCustomerName(prjCstAccInfoQC.getCstNm());
            openAccountValidationRequest.setIdCardNo(prjCstAccInfoQC.getCertNo());
            openAccountValidationRequest.setMobilePhone(prjCstAccInfoQC.getMp());
            openAccountValidationRequest.setBankCardNo(prjCstAccInfoQC.getAccNo());
            openAccountValidationRequest.setCheckCode(verificationCode);
            BaseLogUtils.newLogger("亿联银行调用开户接口Begin：prjId={}, request={}", prjCstAccInfoQC.getPrjId(), JSON.toJSONString(openAccountValidationRequest)).info();
            ResponseData responseData = this.financialService.openAccountValidation(openAccountValidationRequest);
            BaseLogUtils.newLogger("亿联银行调用开户接口End：prjId={}, request={}", prjCstAccInfoQC.getPrjId(), JSON.toJSONString(responseData)).info();
            if (PreloanResultCodeEnum.SUCCESS.getCode().equals(responseData.getCode())) {
                String openAccountStatus = (String) responseData.getData();
                if ("SUCCESS".equals(openAccountStatus)) {
                    PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
                    condition.setIsDel(0);
                    condition.setCstId(prjCstAccInfoQC.getCstId());
                    condition.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_YLBANK);
                    List<PrjCstAccInfoVO> prjCstAccInfoVOS = prjCstAccInfoService.searchList(condition);
                    BaseLogUtils.newLogger("查询客户在亿联下所有账户信息===prjId:{},prjCstAccInfoVOS:{}", prjCstAccInfoQC.getPrjId(), JSON.toJSONString(prjCstAccInfoVOS)).info();
                    if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)){
                        for (PrjCstAccInfoVO vo : prjCstAccInfoVOS) {
                            vo.setAccResCd("0000");
                            vo.setAccResMsg("绑卡成功");
                            vo.setAccNo(prjCstAccInfoQC.getAccNo());
                            vo.setBkCd(prjCstAccInfoQC.getBkCd());
                            vo.setBkNm(prjCstAccInfoQC.getBkNm());
                            vo.setMp(prjCstAccInfoQC.getMp());
                            BaseLogUtils.newLogger("亿联银行修改开户结果Start===prjId:{},vo:{}", prjCstAccInfoQC.getPrjId(), JSON.toJSONString(vo)).info();
                            boolean modify = this.prjCstAccInfoService.modify(vo);
                            BaseLogUtils.newLogger("亿联银行修改开户结果End===prjId:{},modify:{}", prjCstAccInfoQC.getPrjId(), modify).info();
                            if (!modify) {
                                result = new DataResultVO(BaseConstant.IS_YESNO_NO, "绑卡成功，但修改记录失败，请联系管理员");
                                return result;
                            }
                        }
                    }
                } else {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("绑卡失败，请核实！");
                }
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(responseData.getMessage());
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("亿联银行换卡保存失败 " + ex.getMessage()).info();
            ex.printStackTrace();
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("保存失败!");
            BaseLogUtils.newLogger("亿联银行换卡保存失败,系统异常 " + ex.getMessage()).info();
            ex.printStackTrace();
        }
        return result;
    }
}
